package ls

import (
	"fmt"
	"gitee.com/getcharzp/light-ftp/define"
	"github.com/jlaffaye/ftp"
	"github.com/up-zero/gotool/conditionutil"
	"os"
	"strings"
)

func Ls(p string) {
	// p -> [站点名称]:[远程路径]
	// nas:/docs
	arr := strings.Split(p, ":")
	if len(arr) != 2 {
		fmt.Println("远程路径格式错误,格式为 -> [站点名称]:[远程路径]")
		os.Exit(1)
	}
	sysConfig := &define.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		fmt.Println("light ftp config error.", err)
		os.Exit(1)
	}
	var mySite *define.SiteConfig
	for _, site := range sysConfig.Sites {
		if site.Name == arr[0] {
			mySite = &site
			break
		}
	}
	if mySite == nil {
		fmt.Println("light ftp config error. site not found.")
		os.Exit(1)
	}

	client, err := define.NewClient(*mySite)
	if err != nil {
		fmt.Println("light ftp config error.", err)
		os.Exit(1)
	}
	entries, err := client.Conn.List(arr[1])
	if err != nil {
		fmt.Println("light ftp ls error.", err)
		os.Exit(1)
	}

	// print
	for _, entry := range entries {
		// 大小 修改时间 文件的类型 文件名称
		fmt.Printf("%-13s %-15s %-5s %s \n", define.HumanSize(entry.Size),
			entry.Time.Format("2006-01-02 15:04:05"),
			conditionutil.If(entry.Type == ftp.EntryTypeFolder, "路径", "文件"),
			entry.Name)
	}
}
